package com.simon.hse.activity.danger;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.donkingliang.imageselector.utils.ImageSelectorUtils;
import com.google.gson.Gson;
import com.simon.hse.http.Constants;
import com.simon.hse.MyApplication;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.adapter.CommonAdapter;
import com.simon.hse.adapter.CommonEmptyAdapter;
import com.simon.hse.adapter.CommonViewHolder;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.DangerCommonDetailOutput;
import com.simon.hse.http.entity.DropDownOutput;
import com.simon.hse.http.entity.UploadFileOutput;
import com.simon.hse.utils.DateTimeUtils;
import com.simon.hse.utils.DialogUtils;
import com.simon.hse.utils.PopupWindowUtils;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 隐患整改
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_danger_rectify_detail)
public class DangerRectifyDetailActivity extends BaseActivity {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.ll_container)
    LinearLayout mLl_container;

    @ViewInject(R.id.v_cover)
    View mV_cover;

    @ViewInject(R.id.ll_danger_rectify_area)
    LinearLayout mLl_danger_rectify_area;

    @ViewInject(R.id.tv_danger_rectify_area)
    TextView mTv_danger_rectify_area;

    @ViewInject(R.id.ll_danger_rectify_position)
    LinearLayout mLl_danger_rectify_position;

    @ViewInject(R.id.tv_danger_rectify_position)
    TextView mTv_danger_rectify_position;

    @ViewInject(R.id.ll_danger_rectify_category)
    LinearLayout mLl_danger_rectify_category;

    @ViewInject(R.id.tv_danger_rectify_category)
    TextView mTv_danger_rectify_category;

    @ViewInject(R.id.ll_danger_rectify_check)
    LinearLayout mLl_danger_rectify_check;

    @ViewInject(R.id.tv_danger_rectify_check)
    TextView mTv_danger_rectify_check;

    @ViewInject(R.id.ll_danger_rectify_classify)
    LinearLayout mLl_danger_rectify_classify;

    @ViewInject(R.id.tv_danger_rectify_classify)
    TextView mTv_danger_rectify_classify;

    @ViewInject(R.id.ll_danger_rectify_level)
    LinearLayout mLl_danger_rectify_level;

    @ViewInject(R.id.tv_danger_rectify_level)
    TextView mTv_danger_rectify_level;

    @ViewInject(R.id.ll_danger_rectify_date)
    LinearLayout mLl_danger_rectify_date;

    @ViewInject(R.id.tv_danger_rectify_date)
    TextView mTv_danger_rectify_date;

    @ViewInject(R.id.et_danger_rectify_describe)
    EditText mEt_danger_rectify_describe;

    @ViewInject(R.id.rv_pic)
    RecyclerView mRv_pic;

    @ViewInject(R.id.ll_function_file)
    LinearLayout mLl_function_file;

    @ViewInject(R.id.ll_function_bottom)
    LinearLayout mLl_function_bottom;

    private String id;
    private CommonAdapter mCommonAdapter;
    private List<String> mDataBeanList = new ArrayList<>();
    private List<String> mPicList = new ArrayList<>();
    private List<String> mPicIdList = new ArrayList<>();
    private String status;// (/0待审批/1已生效/2审批退回/3验收通过/4验收退回)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTv_common_title.setText("隐患整改");

        initPicRecyclerView();
        initData();
    }

    @Event(value = {R.id.iv_common_left
            , R.id.ll_danger_rectify_area, R.id.ll_danger_rectify_position, R.id.ll_danger_rectify_category, R.id.ll_danger_rectify_classify
            , R.id.ll_danger_rectify_check, R.id.ll_danger_rectify_level, R.id.ll_danger_rectify_date, R.id.iv_add_danger_rectify_pic
            , R.id.tv_danger_rectify_submit, R.id.tv_danger_rectify_save})
    private void clickButton(View view) {
        switch (view.getId()) {
            case R.id.iv_common_left:
                finish();
                break;
            case R.id.ll_danger_rectify_area:
                initCommonPop(mLl_danger_rectify_area, mTv_danger_rectify_area, MyApplication.getInstance().mDangerAreasList);
                break;
            case R.id.ll_danger_rectify_position:
                initCommonPop(mLl_danger_rectify_position, mTv_danger_rectify_position, MyApplication.getInstance().mDangerAreasList);
                break;
            case R.id.ll_danger_rectify_category:
                initCommonPop(mLl_danger_rectify_category, mTv_danger_rectify_category, MyApplication.getInstance().mDangerAreasList);
                break;
            case R.id.ll_danger_rectify_check:
                initCommonPop(mLl_danger_rectify_check, mTv_danger_rectify_check, MyApplication.getInstance().mDangerStandardsList);
                break;
            case R.id.ll_danger_rectify_classify:
                initCommonPop(mLl_danger_rectify_classify, mTv_danger_rectify_classify, MyApplication.getInstance().mDangerClassifyList);
                break;
            case R.id.ll_danger_rectify_level:
                initCommonPop(mLl_danger_rectify_level, mTv_danger_rectify_level, MyApplication.getInstance().mDangerLevelList);
                break;
            case R.id.ll_danger_rectify_date:
                findDate();
                break;
            case R.id.iv_add_danger_rectify_pic:
                ImageSelector.builder()
                        .useCamera(true) // 设置是否使用拍照
                        .setSingle(true)  //设置是否单选
                        .start(DangerRectifyDetailActivity.this, Constants.REQUEST_CODE); // 打开相册
                break;
            case R.id.tv_danger_rectify_submit:
                submitDialog();
                break;
            case R.id.tv_danger_rectify_save:

                break;
        }
    }

    private void initData() {
        Bundle extras = getIntent().getExtras();
        if (extras == null)
            return;
        id = extras.getString("ID");
        status = extras.getString("STATUS");
        switch (status) {//(/0待审批/1已生效/2审批退回/3验收通过/4验收退回)
            case "0":

                break;
            case "1":
                initUnClickable();
                mLl_function_bottom.setVisibility(View.INVISIBLE);
                break;
            case "2":

                break;
            case "3":
                initUnClickable();
                mLl_function_bottom.setVisibility(View.INVISIBLE);
                break;
            case "4":

                break;
        }

        Call<String> call = HttpManager.getInstance().requestService().DANGER_COMMIN_DETAIL(id);
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                DangerCommonDetailOutput dangerCommonDetailOutput = new Gson().fromJson(result, DangerCommonDetailOutput.class);
                if (dangerCommonDetailOutput.getResult().equals("Success")) {
                    DangerCommonDetailOutput.DataBean dataBean = dangerCommonDetailOutput.getData();
                    for (DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean : MyApplication.getInstance().mDangerAreasList) {
                        if (valueBean.getKey().equals(dataBean.getRiskRegion())) {
                            mTv_danger_rectify_area.setText(valueBean.getValue());
                        }
                    }
                    mTv_danger_rectify_position.setText(dataBean.getRiskPosition());
                    mTv_danger_rectify_category.setText(dataBean.getOrganizationType());
                    for (DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean : MyApplication.getInstance().mDangerStandardsList) {
                        if (valueBean.getKey().equals(dataBean.getInspectType())) {
                            mTv_danger_rectify_check.setText(valueBean.getValue());
                        }
                    }
                    for (DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean : MyApplication.getInstance().mDangerClassifyList) {
                        if (valueBean.getKey().equals(dataBean.getRiskType())) {
                            mTv_danger_rectify_classify.setText(valueBean.getValue());
                        }
                    }
                    for (DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean : MyApplication.getInstance().mDangerLevelList) {
                        if (valueBean.getKey().equals(dataBean.getRiskLevel())) {
                            mTv_danger_rectify_level.setText(valueBean.getValue());
                        }
                    }

                    String discoveryTime = dataBean.getDiscoveryTime();
                    mTv_danger_rectify_date.setText(DateTimeUtils.convertCustomDate(discoveryTime));

                    mEt_danger_rectify_describe.setText(dataBean.getRiskDescription());
                } else {
                    ToastUtils.getInstance().showShortToastBottom(dangerCommonDetailOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 排查情况Pop
     */
    private void initCommonPop(LinearLayout mLl, final TextView mTv, final List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mList) {
        View inflate = LayoutInflater.from(DangerRectifyDetailActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(DangerRectifyDetailActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(DangerRectifyDetailActivity.this, R.layout.layout_item_common_more_department, mList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<DropDownOutput.DataBean.DataDicListBean.ValueBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, DropDownOutput.DataBean.DataDicListBean.ValueBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getValue());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean = mList.get(position);
                mTv.setText(valueBean.getValue());
                PopupWindowUtils.getInstance().closePop();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(DangerRectifyDetailActivity.this, inflate, mLl);
    }

    /**
     * 隐患发现时间
     */
    private void findDate() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        startDate.set(1949, 1, 1);
        String currentYMD = "";
        String oldTime = mTv_danger_rectify_date.getText().toString();
        if (TextUtils.isEmpty(oldTime)) {
            currentYMD = DateTimeUtils.getCurrentYMD();
        } else {
            currentYMD = oldTime.split(" ")[0];
        }
        String[] split0 = currentYMD.split("-");
        selectedDate.set(Integer.parseInt(split0[0]), Integer.parseInt(split0[1]) - 1, Integer.parseInt(split0[2]));
        String[] split1 = DateTimeUtils.getCurrentYMD().split("-");
        endDate.set(Integer.parseInt(split1[0]), Integer.parseInt(split1[1]) - 1, Integer.parseInt(split1[2]));

        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(DangerRectifyDetailActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat sdf_ymd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                mTv_danger_rectify_date.setText(sdf_ymd.format(date));
            }
        })
                .setType(new boolean[]{true, true, true, true, true, false})// 默认全部显示
                .setLabel("年", "月", "日", "时", "分", "")//默认设置为年月日时分秒
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .build();

        pvTime.show();
    }

    //图片展示
    private void initPicRecyclerView() {
        GridLayoutManager glm = new GridLayoutManager(DangerRectifyDetailActivity.this, 4);
        mRv_pic.setLayoutManager(glm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRv_pic.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRv_pic.setItemAnimator(new DefaultItemAnimator());
        mRv_pic.setNestedScrollingEnabled(false);

        mCommonAdapter = new CommonAdapter(DangerRectifyDetailActivity.this, R.layout.layout_item_pic, mPicList);
        mCommonAdapter.setItemDatasListener(new CommonAdapter.ItemDatasListener<String>() {
            @Override
            public void setItemDatas(CommonViewHolder holder, String uri, int position) {
                ImageView iv_item = holder.getView(R.id.iv_item);
                Glide.with(DangerRectifyDetailActivity.this).load(uri).into(iv_item);
            }
        });

        mCommonAdapter.setOnItemClickListener(new CommonAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {

            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {
                mPicList.remove(position);
                mPicIdList.remove(position);
                mCommonAdapter.notifyDataSetChanged();
            }
        });

        mRv_pic.setAdapter(mCommonAdapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 更新头像
        if (requestCode == Constants.REQUEST_CODE && data != null) {
            ArrayList<String> images = data.getStringArrayListExtra(
                    ImageSelectorUtils.SELECT_RESULT);
            mPicList.clear();
            mPicList.addAll(images);
            if (mPicList.isEmpty()) {
                mRv_pic.setVisibility(View.GONE);
            } else {
                mRv_pic.setVisibility(View.VISIBLE);
                mCommonAdapter.notifyDataSetChanged();
                uploadImages();
            }
        }
    }

    /**
     * 上传照片
     */
    private void uploadImages() {
        if (mPicList.isEmpty())
            return;
        for (String path : mPicList) {
            File file = new File(path);
            if (!file.exists())
                break;
            final RequestBody requestFile =
                    RequestBody.create(MediaType.parse("application/otcet-stream"), file);
            MultipartBody.Part body = MultipartBody.Part.createFormData("files", file.getName(), requestFile);

            Call<String> call = HttpManager.getInstance().requestService().UPLOAD_FILE(body);
            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    UploadFileOutput uploadFileOutput = new Gson().fromJson(response.body(), UploadFileOutput.class);
                    if (uploadFileOutput.getResult().equals("Success")) {
                        String id = uploadFileOutput.getData().get(0).getId();
                        mPicIdList.add(id);
                    }
                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    // Log.i("Simon", "uploadImages onFailure = " + t.getMessage());
                }
            });
        }
    }

    /**
     * 提交确认框
     */
    private void submitDialog(){
        View inflate = LayoutInflater.from(DangerRectifyDetailActivity.this).inflate(R.layout.layout_submit_dialog, null);
        TextView tv_dialog_title = inflate.findViewById(R.id.tv_dialog_title);
        tv_dialog_title.setText("提示");
        TextView tv_dialog_content = inflate.findViewById(R.id.tv_dialog_content);
        tv_dialog_content.setText("请您确保隐患已整改完毕");
        inflate.findViewById(R.id.tv_dialog_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.getInstance().exitDialog();
            }
        });
        inflate.findViewById(R.id.tv_dialog_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.getInstance().exitDialog();
            }
        });
        DialogUtils.getInstance().createDialog(DangerRectifyDetailActivity.this,inflate, Gravity.CENTER,0.8,0.3);
    }

    /**
     * 设置页面不可点击
     */
    private void initUnClickable() {
        mLl_container.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int height = mLl_container.getMeasuredHeight();
                int width = mLl_container.getMeasuredWidth();

                ViewGroup.LayoutParams layoutParams = mV_cover.getLayoutParams();
                layoutParams.height = height;
                mV_cover.setLayoutParams(layoutParams);
                mV_cover.setOnClickListener(null);
            }
        });
    }
}
